﻿using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.Threading;
using System.Security.Cryptography;
using System.Web;
using System.Text.RegularExpressions;
using CM.UserCenter.Common;
using QL.Web;
using CM.Resources.Web.Models;
using QL.Core.Caching;
using CM.Resources.Web.Comm.Log;
using QL.Core.Log;

namespace CM.Resources.Web.Controllers
{
    /// <summary>
    /// 文件处理类
    /// </summary>
    public class FileHandler
    {
        static private ILogger log = RYLogger.GetLogger("HttpHandleController");
        /// <summary>
        /// 获取文件名
        /// </summary>
        /// <returns></returns>
        public static string getFileName(string FileName)
        {
            return Guid.NewGuid().ToString() + getFileExtension(FileName);
        }
        /// <summary>
        /// 获取文件存储目录
        /// </summary>
        /// <param name="root">文件根目录</param>
        /// <param name="SiteName">站点文件夹名</param>
        /// <returns>文件存储目录</returns>
        public static string getFilePath(string Root, string SiteName)
        {
            //站点目录
            string path = string.Format(@"{0}\{1}", Root, SiteName);
            //动态生成目录(年/月/日/小时)
            string FullPath = string.Format(@"{0}\{1}\{2}\{3}\{4}", path, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, DateTime.Now.Hour);
            Directory.CreateDirectory(FullPath);
            return FullPath;
        }
        /// <summary>
        /// 写文件
        /// </summary>
        /// <param name="path"></param>
        /// <param name="content"></param>
        public static void writeFile(String path, string content)
        {
            FileStream f = new FileStream(path, FileMode.Create);
            FileInfo fi = new FileInfo(path);
            fi.Attributes = FileAttributes.Hidden;//设置文件为隐藏
            byte[] bytes = Encoding.UTF8.GetBytes(content);
            f.Write(bytes, 0, bytes.Length);
            f.Close();
        }
        /// <summary>
        /// 获取文件的MD5信息
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static string FileMD5(Stream s)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            byte[] arr = md5.ComputeHash(s);
            string str = BitConverter.ToString(arr);
            str = str.Replace("-", "");
            return str;
        }
        /// <summary>
        /// 获取文件后缀
        /// </summary>
        /// <param name="FileName"></param>
        /// <returns></returns>
        public static string getFileExtension(string FileName)
        {
            int index = FileName.LastIndexOf(".");
            return index == -1 ? ".txt" : FileName.Substring(index);
        }
        /// <summary>
        /// 检查路径是否合法
        /// 不能包含../或..\
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public static bool ValidatePath(string path)
        {
            Regex reg = new Regex(@"\.\s*\.\s*[/,\\]");
            Match result = reg.Match(path);
            return result.Value == "";
        }


        static MemoryCaching cache = new MemoryCaching("file");

        /// <summary>
        /// 检查IP是否合法
        /// 资源服务器管理后台限制IP访问
        /// </summary>
        /// <param name="IP"></param>
        /// <returns></returns>
        public static bool ValidateRemoteIP()
        {
            string ip = WebContext.Request.RemoteAddress;
            string limits = Configuration.Default.LimitIP;
            if (!string.IsNullOrEmpty(limits))
            {
                return cache.GetOrAdd<bool>($"{limits}_{ip}", () =>
                {
                    if (ip.Equals("::1")) { return true; }
                    if (ip.Equals("127.0.0.1")) { return true; }
                    if (IPAddress.TryParse(ip, out IPAddress clientIp))
                    {

                        if (!string.IsNullOrEmpty(limits))
                        {
                            var checkList = cache.GetOrAdd<List<IPCheckInfo>>(limits, () =>
                            {
                                List<IPCheckInfo> list = new List<IPCheckInfo>();
                                var strArray = limits.Split(',');
                                foreach (var item in strArray)
                                {
                                    var ipAndMask = item.Split('/');
                                    if (ipAndMask.Length > 1)
                                    {
                                        if (int.TryParse(ipAndMask[1], out int subMaskBit))
                                        {
                                            IPAddress mask = null;
                                            try
                                            {
                                                mask = SubnetMask.CreateByNetBitLength(subMaskBit);
                                            }
                                            catch (Exception ex)
                                            {

                                                log.Error(ex, "");
                                            }
                                            if (mask != null)
                                            {
                                                if (IPAddress.TryParse(ipAndMask[0], out IPAddress address))
                                                {
                                                    list.Add(new IPCheckInfo()
                                                    {
                                                        Address = address,
                                                        IsIpAddress = false,
                                                        SubMask = mask
                                                    });
                                                }
                                                else
                                                {
                                                    log.Error("配置错误:{0}", item);
                                                }
                                            }
                                        }
                                        else
                                        {
                                            log.Error("配置错误:{0}", item);
                                        }
                                    }
                                    else
                                    {
                                        if (IPAddress.TryParse(item, out IPAddress address))
                                        {
                                            list.Add(new IPCheckInfo()
                                            {
                                                Address = address,
                                                IsIpAddress = true
                                            });
                                        }
                                        else
                                        {
                                            log.Error("配置错误:{0}", item);
                                        }
                                    }
                                }
                                return list;
                            });

                            if (checkList.Count > 0)
                            {
                                var checkResult = checkList.AsParallel().Select(info =>
                                {
                                    if (info.IsIpAddress)
                                    {
                                        return info.Address.Equals(clientIp);
                                    }
                                    else
                                    {
                                        return clientIp.IsInSameSubnet(info.Address, info.SubMask);
                                    }

                                }).Contains(true);
                                return checkResult;
                            }
                            else
                            {
                                return false;
                            }
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                });
            }
            else
            {

                return false;
            }



        }
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="File">文件</param>
        /// <param name="FullPath">路径</param>
        public static void save(string FilePath, HttpPostedFileBase File, FileData FileData)
        {
            //文件
            File.SaveAs(FilePath);
            //文件描述信息
            string MetaPath = string.Format("{0}.txt", FilePath);
            FileData.FileMD5 = FileMD5(File.InputStream);
            string FileMeta = JsonConvert.SerializeObject(FileData);
            writeFile(MetaPath, FileMeta);
        }
    }
}
